// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-17 21:26
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.DataStruct.Tree.Trie;

public class WordDictionary {

    class Node {
        boolean isEnd;
        Node[] tns = new Node[26];

        public Node() {
        }
    }

    Node root;

    /**
     * 字典树的升级版本，其中search可以实现.的任意匹配
     */
    public WordDictionary() {
        root = new Node();
    }

    public void addWord(String word) {
        Node p = root;
        for (int i = 0; i < word.length(); i++) {
            int u = word.charAt(i) - 'a';
            if (p.tns[u] == null) {
                p.tns[u] = new Node();
            }
            p = p.tns[u];
        }
        p.isEnd = true;
    }

    /**
     * 查找： 1 出现 .
     *
     * @param word
     * @return
     */
    public boolean search(String word) {
        Node p = root;
        return searchT(root, word);
    }

    private boolean searchT(Node p, String word) {
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) != '.') {
                int u = word.charAt(i) - 'a';
                if (p.tns[u] == null) {
                    return false;
                }
                p = p.tns[u];
            } else {
                // 当前字符是'.'，通配符，可以匹配任意字符
                for (int j = 0; j < 26; j++) {
                    if (p.tns[j] != null && searchT(p.tns[j], word.substring(i + 1, word.length()))) {
                        return true;
                    }
                }
                return false;
            }
        }
        return p.isEnd;
    }
}
/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */